package com.rds.material.service.impl;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.rds.common.ServiceException;
//import com.rds.common.api.workflow.IRdaWorkflowApi;
import com.rds.common.api.material.IMaterialBillApi;
import com.rds.common.api.material.domain.*;
import com.rds.common.utils.DateUtils;
import com.rds.common.utils.SecurityUtils;
import com.rds.common.utils.uuid.SnowFlakeUtils;
import com.rds.material.mapper.MaterialBillMapper;
import com.rds.material.service.*;
import com.rds.material.utils.WorkspaceUtils;
import com.rds.system.domain.Sharing;
import com.rds.system.service.*;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 材料清单Service业务层处理
 *
 * @author rds
 * @date 2021-08-17
 */
@Service
public class MaterialBillServiceImpl implements IMaterialBillService, IMaterialBillApi
{
    @Autowired
    private IRdaPartDynamicattributeService rdaPartDynamicattributeService;

//    @Autowired
//    private RdaWorkflowTempleteScopeService rdaWorkflowTempleteScopeService;


//    @Autowired
//    private IRdaWorkflowApi rdaWorkflowTempleteScopeService;

    @Autowired
    private IRdaPartsRelService rdaPartsRelService;
    @Autowired
    private IRdaPartService rdaMaterialService;

    @Autowired
    private MaterialBillMapper materialBillMapper;

    @Autowired
    private IRdaNameCodeService rdaNameCodeService;

    @Autowired
    private IRdaTypeService rdaTypeService;

    @Autowired
    private IRdaPolicyService rdaPolicyService;

    @Autowired
    private IRdaStateService rdaStateService;

    @Autowired
    private IRdaPartDynamicattributevalueService rdaPartDynamicattributevalueService;
    /**
     * 查询材料清单
     * @param id 材料清单ID
     * @return 材料清单
     */
    @Override
    public MaterialBill selectMaterialBillById(Long id)
    {
        return materialBillMapper.selectMaterialBillById(id);
    }

    @Override
    public List<MaterialBill> selectMaterialBillByIds(List<Long> ids)
    {
        return materialBillMapper.selectMaterialBillByIds(ids);
    }


    @Override
    public List<Map<String, Object>> selectMaterialBillAndRdaPartRel(MaterialBill materialBill) {
        return materialBillMapper.selectMaterialBillAndRdaPartRel(materialBill);
    }


    /**
     * 查询材料清单
     * @param parentid 材料清单ID
     * @param materialid 物料ID
     * @return 项目WBS
     */
    @Override
    public MaterialBill selectMaterialBillByMid(@Param("parentid") Long parentid,@Param("materialid")Long materialid)
    {
        return materialBillMapper.selectMaterialBillByMid(parentid,materialid);
    }

    /**
     * 查询材料清单列表
     * @param materialBill 材料清单
     * @return 材料清单
     */
    @Override
    public List<MaterialBill> selectMaterialBillList(MaterialBill materialBill)
    {
        return materialBillMapper.selectMaterialBillList(materialBill);
    }

    @Override
    public List<MaterialBill> selectMaterialBillListLJRel(MaterialBill materialBill) {
        return materialBillMapper.selectMaterialBillListLJRel(materialBill);
    }

    /**
     * 查询材料清单下级列表
     * @param materialBill 材料清单
     * @return 材料清单集合
     */
    @Override
    public List<MaterialBill> selectMaterialBillLowerList(MaterialBill materialBill){
        return materialBillMapper.selectMaterialBillList(materialBill);
    }


    /**
     * 新增材料清单
     * @param materialBill 材料清单
     * @return 结果
     */
    @Override
    public int insertMaterialBill(MaterialBill materialBill,String type)
    {
        RdaPartsRel rdaPartsRel = new RdaPartsRel();
        String nametype = materialBill.getNametype();
        Long userId = SecurityUtils.getUserId();
        materialBill.setOwnerid(userId.intValue());
        Long newId=SnowFlakeUtils.nextId();
        materialBill.setId(SnowFlakeUtils.nextId());
        materialBill.setCreateTime(DateUtils.getNowDate());
        materialBill.setModifyTime(DateUtils.getNowDate());
        Long materialid=materialBill.getMaterialid();
        Long parentid=materialBill.getParentid();
        if(parentid==0){
            materialBill.setParentid(materialid);
        }
        materialBill.setMaterialid(materialid);

        rdaPartsRel.setId(SnowFlakeUtils.nextId());
        rdaPartsRel.setQuantity(materialBill.getNumber().longValue());
        rdaPartsRel.setRelName("Classfited Item");
        rdaPartsRel.setFromid(materialBill.getId());
        rdaPartsRel.setToid(materialBill.getMaterialid());
        rdaPartsRel.setTotype(materialBill.getTypeid());
        rdaPartsRel.setCreateTime(DateUtils.getNowDate());
        rdaPartsRel.setUpdateTime(DateUtils.getNowDate());
        rdaPartsRel.setParentId(materialBill.getParentid());
        //获取自动编码
        if (materialBill.getCode() == null) {
            if (nametype!=null){
                materialBill.setCode(nametype.concat(rdaNameCodeService.getNewCodeNameNo(Long.valueOf(materialBill.getTypeid()), "")));
            }else {
                materialBill.setCode(rdaNameCodeService.getNewCodeNameNo(Long.valueOf(materialBill.getTypeid()),""));
            }
        }
        if("1".equals(type)){//新增同级
            MaterialBill mb=materialBillMapper.selectMaterialBillById(parentid);
            materialBill.setParentid(mb.getParentid());
            Integer level=mb.getLevel();
            materialBill.setLevel(level);
            int num=materialBillMapper.insertMaterialBill(materialBill);
            if(num>0){
                if(level>=1){
                    //更新级别号
                    updateorderforupdate(mb.getParentid(),materialid,"");
                    //更新顺序号
                    updateRdorder(materialid);
                }
            }
            return num;
        }else if("2".equals(type)){//新增上级
            MaterialBill mb=materialBillMapper.selectMaterialBillById(parentid);
            MaterialBill mb1=materialBillMapper.selectMaterialBillById(mb.getParentid());
            if(mb1==null){
                return -1;
            }
            materialBill.setParentid(mb1.getId());
            materialBill.setLevel(mb.getLevel());
            materialBill.setProjectid(materialid);
            int num=materialBillMapper.insertMaterialBill(materialBill);
            //修改下级父ID为现添加上级的ID
            MaterialBill oldMb=new MaterialBill();
            oldMb.setId(parentid);
            oldMb.setParentid(newId);
            oldMb.setLevel(mb.getLevel()+1);
            materialBillMapper.updateMaterialBill(oldMb);
            updateLevel(mb1.getId(),mb1.getLevel());
            updateorderforupdate(mb1.getId(),materialid,"");
            return num;
        }else{//插入下一级
            Integer level=materialBill.getLevel()+1;//下一级
            materialBill.setLevel(level);
            int num=materialBillMapper.insertMaterialBill(materialBill);
            if(num>0){
                if(level>=1){//插入成功后更新顺序号，级别号
                    updateorderforupdate(parentid,materialid,"");
                    updateRdorder(materialid);
                }
            }
            rdaPartsRel.setLevel(materialBill.getLevel().longValue());
            rdaPartsRel.setFindnumber(materialBill.getRank().toString());
            rdaPartsRelService.insertRdaPartsRel(rdaPartsRel);
            return num;
        }
    }

    @Override
    public int insertMaterialBills(MaterialBill materialBill) {
        return materialBillMapper.insertMaterialBill(materialBill);
    }


    /**
     * 修改材料清单
     * @param materialBill 材料清单
     * @return 结果
     */
    @Override
    public int updateMaterialBill(MaterialBill materialBill)
    {
        materialBill.setModifyTime(DateUtils.getNowDate());
        return materialBillMapper.updateMaterialBill(materialBill);
    }

    /**
     * 批量删除材料清单
     * @param ids 需要删除的材料清单ID
     * @return 结果
     */
    @Override
    public int deleteMaterialBillByIds(Long[] ids)
    {
        int num=0;
        int rows;
        for(Long id:ids){
            rows=materialBillMapper.deleteMaterialBillById(id);
            if(rows>0){
                num++;
            }
        }
        return num;
    }

    /**
     * 删除材料清单
     * @param id 材料清单ID
     * @return 结果
     */
    @Override
    public int deleteMaterialBillById(Long id)
    {
        return materialBillMapper.deleteMaterialBillById(id);
    }

    /**
     * 删除材料清单
     * @param id 物料ID
     * @return 结果
     */
    @Override
    public int deleteMaterialBillByMid(Long id)
    {
        return materialBillMapper.deleteMaterialBillByMid(id);
    }

    /**
     * 查询材料清单 版本信息
     * @param toid id
     * @return 材料清单集合
     */
    @Override
    public MaterialBill selectMaterialBill(@Param("toid")Long toid){
        return materialBillMapper.selectMaterialBill(toid);
    }


    /**
     * 根据ID查询材料清单下级信息
     * @param id id
     * @return 材料清单集合
     */
    @Override
    public List<MaterialBill> selectMaterialBillSubordinate (@Param("id") Long id){
        return materialBillMapper.selectMaterialBillSubordinate(id);
    }

    /**
     * 更新级别号
     * @param materialid
     * @return 结果
     */
    public int updateOrder(Long materialid){
        return updateRdorder(materialid);
    }

    /**
     * 更新级别号
     * @param materialid
     * @return 结果
     */
    public int updateRank(Long parentid,Long materialid,String parentrank){
        return updateorderforupdate(parentid, materialid, parentrank);
    }

    /**
     * 更新级别号程序入口，新增WBS任务时调用，传递父项对象属性
     * @param materialid
     * @return 结果
     */
    public int updateorderforupdate(Long parentid,Long materialid,String parentrank) {
        //传入的父id、物料id和父级排名
        MaterialBill materialBill=new MaterialBill();
        materialBill.setParentid(parentid);
        if(parentid>0){
            //先查找父id的物料信息
            MaterialBill bill = materialBillMapper.selectMaterialBillById(parentid);
            if(bill!=null){
                //得到父级排名
                parentrank = bill.getRank();
            }
        }else{
            //如过查不到父id，设置父id为物料号（一级目录）
            materialBill.setParentid(materialid);
        }
        materialBill.setMaterialid(materialid);
        //查找父id下的所有物料
        List<MaterialBill> list= materialBillMapper.selectMaterialBillList(materialBill);
        List<MaterialBill> nullList=new ArrayList<>();
        int i=0;
        int num =0;
        //更新级别号开始
        for(MaterialBill mb:list){
            String newrank;
            //对于已有级别号为空的物料，将其添加到nullList中
            if(mb.getRank()==null){
                nullList.add(mb);
            }else{
                i++;
                if(mb.getLevel()==1 || parentrank==null || "".equals(parentrank)){
                    newrank= String.valueOf(i);
                }else{
                    newrank= parentrank.trim()+"."+String.valueOf(i).trim();
                }
                if(!mb.getRank().equals(newrank)){
                    MaterialBill newmb=new MaterialBill();
                    newmb.setId(mb.getId());
                    newmb.setRank(newrank);
                    num = materialBillMapper.updateMaterialBill(newmb);
                    if(num>0){
                        updateorderforupdate(mb.getId(),mb.getMaterialid(),newrank);
                    }
                }
            }
        }
        if(nullList.size()>0){
            int k=i;
            for(MaterialBill mb1:nullList){
                k++;
                String newrank;
                if(mb1.getLevel()==1 || parentrank==null || "".equals(parentrank)){
                    newrank= String.valueOf(k);
                }else{
                    newrank= parentrank.trim()+"."+String.valueOf(k).trim();
                }
                if(mb1.getRank()==null || !mb1.getRank().equals(newrank)){
                    MaterialBill newmb1=new MaterialBill();
                    newmb1.setId(mb1.getId());
                    newmb1.setRank(newrank);
                    num = materialBillMapper.updateMaterialBill(newmb1);
                    if(num>0){
                        updateorderforupdate(mb1.getId(),mb1.getMaterialid(),newrank);
                    }
                }
            }
        }
        return num;
    }

    /**
     * 更新level
     */
    public void updateLevel(Long id,Integer level){
        MaterialBill materialBill = new MaterialBill();
        materialBill.setMaterialid(id);
        materialBill.setLevel(level);
        List<MaterialBill> materialBillList = selectTreeList(materialBill);
        for (MaterialBill bill : materialBillList) {
            if (!bill.getLevel().equals(bill.getLevels())){
                bill.setLevel(bill.getLevels());
                updateMaterialBill(bill);
            }
        }
    }

    /**
     * 更新顺序号程序入口
     * @param materialid
     * @return 结果
     */
    public int updateRdorder(Long materialid) {
        MaterialBill bill=new MaterialBill();
        bill.setMaterialid(materialid);
//        bill.setLevel(1);
        List<MaterialBill> list= materialBillMapper.selectMaterialBillList(bill);
        int num =0;
        int i=1;
        //更新顺序号开始
        for(MaterialBill mb:list){
            if(mb.getRdorder()==null || i!=mb.getRdorder()){
                MaterialBill newmb=new MaterialBill();
                newmb.setId(mb.getId());
                newmb.setRdorder(i);
                num =materialBillMapper.updateMaterialBill(newmb);
                i++;
                i=updateLowerRdorder(i,mb.getId());
            }else{
                i++;
            }
        }
        return num;
    }

    /**
     * 更新下级顺序号程序入口
     * @return 结果
     */
    public int updateLowerRdorder(int i,Long id) {
        MaterialBill bill=new MaterialBill();
        bill.setParentid(id);
        List<MaterialBill> lowerList= materialBillMapper.selectMaterialBillList(bill);
        if(lowerList.size()>0){
            for (MaterialBill lowerMb:lowerList){
                if(lowerMb.getRdorder()==null||i!=lowerMb.getRdorder()){
                    MaterialBill newmb=new MaterialBill();
                    newmb.setId(lowerMb.getId());
                    newmb.setRdorder(i);
                    materialBillMapper.updateMaterialBill(newmb);
                    i++;
                    i=updateLowerRdorder(i,lowerMb.getId());
                }
            }
        }
        return i;
    }

    /**
     * 克隆EBOM
     * @param materialBill
     * @return EBOM
     */
    public int cloneEBOM(MaterialBill materialBill){
        int num=0;
        List<MaterialBill> mbList=materialBillMapper.selectCloneEBOM(materialBill);
        if(mbList.size()==0){
            return -1;
        }
        for(MaterialBill mb:mbList){
            Long id=SnowFlakeUtils.nextId();
            mb.setId(id);
            mb.setCreateTime(DateUtils.getNowDate());
            mb.setModifyTime(DateUtils.getNowDate());
            num=materialBillMapper.insertMaterialBill(mb);
        }
        //修改选择的非最上层的下面的task的parentid
        materialBillMapper.updateEBOMTask(materialBill);
        //修改选择的最上层的task的parentid
        materialBill.setParentid(materialBill.getTmpParentid());
        materialBillMapper.updateEBOMTaskUpper(materialBill);
        return num;
    }

    /**
     * 根据id查询所有上层级(包括自己)
     * @param id
     * @return
     */
    public List<MaterialBill> getHierarchyU(Long id) {
        MaterialBill materialBill = selectMaterialBillById(id);
        List<MaterialBill> result = new ArrayList<>();
        if (materialBill!=null) {
            result.add(0,materialBill);
            List<MaterialBill> children = getHierarchyU(materialBill.getParentid());
            result.addAll(0,children);
        }
        return result;
    }

    /**
     * 查找下级rank的最大值,并最后一个小数点重新赋值
     */
    public String MaxRank(Long id,int num){
        MaterialBill mb = new MaterialBill();
        mb.setParentid(id);
        List<MaterialBill> MaterialBills=selectMaterialBillList(mb);
        if (CollectionUtils.isEmpty(MaterialBills)){
            MaterialBill materialBill = selectMaterialBill(id);
            if (materialBill==null){
                return "1";
            }else {
                return materialBill.getRank()+".1";
            }
        }
        String maxRank = MaterialBills.get(0).getRank(); // 初始化maxRank为第一个MaterialBill的rank值
        // 遍历MaterialBills列表
        for (MaterialBill materialBill : MaterialBills) {
            String rank = materialBill.getRank();

            // 比较rank值与maxRank的大小关系
            if (rank.compareTo(maxRank) > 0) {
                maxRank = rank;
            }
        }
        if (maxRank.contains(".")){
            // 获取最后一位小数点上的数字，并加1
            String[] rankParts = maxRank.split("\\.");
            int lastNumber = Integer.parseInt(rankParts[rankParts.length - 1]);
            lastNumber=lastNumber+num;

            // 将加1后的数字与其他分割的部分重新组合，得到新的rank值
            String newRank = "";
            for (int i = 0; i < rankParts.length - 1; i++) {
                newRank += rankParts[i] + ".";
            }
            newRank += lastNumber;
            return newRank;
        }
        return String.valueOf(Integer.parseInt(maxRank)+ 1);
    }


    /**
     * 同级下指定id后的rank自动加1
     * @param materialBillList
     * @param id
     * @return
     */
    public List<MaterialBill> updateRank(List<MaterialBill> materialBillList,Long id) {
        class RankWrapper {
            boolean updateRank = false;
        }
        RankWrapper rankWrapper = new RankWrapper();

        List<MaterialBill> updatedList = materialBillList.stream()
                .map(materialBill -> {
                    if (rankWrapper.updateRank) {
                        String rank = materialBill.getRank();
                        if (rank.contains(".")){
                            String[] rankParts = rank.split("\\.");
                            int lastNumber = Integer.parseInt(rankParts[rankParts.length - 1]);
                            lastNumber += 1;
                            String newRank = "";
                            for (int i = 0; i < rankParts.length - 1; i++) {
                                newRank += rankParts[i] + ".";
                            }
                            newRank += lastNumber;
                            materialBill.setRank(newRank);
                        }else {
                            materialBill.setRank(String.valueOf(Integer.parseInt(rank)+ 1));
                        }

                    }
                    if (materialBill.getId().equals(id)) {
                        rankWrapper.updateRank = true;
                    }
                    return materialBill;
                })
                .collect(Collectors.toList());

        return updatedList;
    }



    /**
     * 根据id查询所有子层级
     * @param parentId
     * @return
     */
    @Override
    public List<MaterialBill> getHierarchy(Long parentId) {
        MaterialBill materialBill = new MaterialBill();
        materialBill.setParentid(parentId);
        List<MaterialBill> materialBills = materialBillMapper.selectMaterialBillList(materialBill);
        List<MaterialBill> result = new ArrayList<>();
        for (MaterialBill data : materialBills) {
            if (data.getParentid().equals(parentId)) {
                result.add(data);
                List<MaterialBill> children = getHierarchy(data.getId());
                result.addAll(children);
            }
        }
        return result;
    }

    @Override
    public List<MaterialBill> selectMaterialBillByAll(MaterialBill materialBill) {
        return materialBillMapper.selectMaterialBillByAll(materialBill);
    }
    @Override
    public List<MaterialBill> selectMaterialBillByUnasso(MaterialBill materialBill) {
        return materialBillMapper.selectMaterialBillByUnasso(materialBill);
    }

    @Override
    public void removeEbom(Long[] ids) {
        for (Long id : ids) {
            MaterialBill materialBill = materialBillMapper.selectMaterialBillById(id);
            MaterialBill materialBillP = new MaterialBill();
            materialBillP.setName(materialBill.getName());
            materialBillP.setTypeid(materialBill.getTypeid());
            materialBillP.setRevision(materialBill.getRevision());
            List<MaterialBill> materialBillList = materialBillMapper.selectMaterialBillList(materialBillP);
            //如果存在一个就段开关系
            if (materialBillList.size()==1){
                materialBill.setParentid(-1L);
                materialBillMapper.updateMaterialBill(materialBill);
            }
            //如果存在多个就删除数据
            else {
                materialBillMapper.deleteMaterialBillById(id);
            }

        }
    }


    @Override
    public void rankSort(Long[] ids) {
        for (Long id : ids) {
            MaterialBill materialBill = selectMaterialBillById(id);
            int i = updateRank(materialBill.getParentid(), materialBill.getMaterialid(), materialBill.getRank());
            if (i>0){

            }
        }

    }


    // TODO: 2023/11/17 修改原有
//    /**
//     * 插入现有零件作为子级
//     * @param rdaPmsassignRel
//     * @return
//     */
//    public void InsertExistAsChild(RdaPmsassignRel rdaPmsassignRel){
//        //表单选中的id
//        String idsStr=rdaPmsassignRel.getIds();
//        String[] ids =idsStr.split(",");
//        ArrayList<MaterialBill> list = new ArrayList<>();
//        for (String id : ids) {
//            list.add(selectMaterialBillById(Long.valueOf(id)));
//        }
//        //表格选中的id
//        MaterialBill materialBillT;
//        if ("0".equals(rdaPmsassignRel.getPmsid())L){
//            //雪花id
//            for (MaterialBill materialBillF : list) {
//                long lt = SnowFlakeUtils.nextId();
//                materialBillF.setParentid(rdaPmsassignRel.getProjectid());
//                materialBillF.setId(lt);
//                materialBillF.setLevel(1);
//                materialBillF.setNumber(1.0);
//                materialBillF.setMaterialid(rdaPmsassignRel.getProjectid());
//                materialBillMapper.insertMaterialBill(materialBillF);
//                updateorderforupdate(materialBillF.getId(),materialBillF.getMaterialid(),materialBillF.getRank());
//                updateRdorder(materialBillF.getMaterialid());
//            }
//        }else {
//            //查询表格选中的所有下级
//            //雪花id
//            materialBillT=selectMaterialBillById(rdaPmsassignRel.getPmsid());
//            for (MaterialBill materialBillF : list) {
//                long lt = SnowFlakeUtils.nextId();
//                materialBillF.setParentid(materialBillT.getId());
//                materialBillF.setId(lt);
//                System.out.println("====================="+(materialBillT.getLevel()+1));
//                materialBillF.setLevel((materialBillT.getLevel()+1));
//                materialBillF.setMaterialid(rdaPmsassignRel.getProjectid());
//                materialBillMapper.insertMaterialBill(materialBillF);
//                updateorderforupdate(rdaPmsassignRel.getPmsid(),materialBillF.getMaterialid(),materialBillF.getRank());
//                updateRdorder(materialBillF.getMaterialid());
//            }
//        }
//    }

    /**
     * 插入现有零件作为子级
     * @param rdaPmsassignRel
     * @return
     */
    public void InsertExistAsChild(Sharing rdaPmsassignRel){
        //表单选中的id
        String idsStr=rdaPmsassignRel.getIds();
        String[] ids =idsStr.split(",");
        ArrayList<MaterialBill> list = new ArrayList<>();
        for (String id : ids) {
            list.add(selectMaterialBillById(Long.valueOf(id)));
        }
        /**
         * 问题记录
         * 选中顶级物料参数为
         * ids:表单选中的id
         * pmsid:0
         * projectid:顶级物料的id
         * toid:0
         * 所以要加一层判断
         */
        //表格选中的id
        MaterialBill materialBillT = null;
        if ("0".equals(rdaPmsassignRel.getPmsid())){
            System.out.println("0.equals(rdaPmsassignRel.getPmsid())====================");
            materialBillT=selectMaterialBillById(rdaPmsassignRel.getProjectid());
            rdaPmsassignRel.setProjectid(materialBillT.getMaterialid());
        }else {
            materialBillT = selectMaterialBillById(Long.parseLong(rdaPmsassignRel.getPmsid()));
        }
        MaterialBill materialBill = new MaterialBill();
        //查找未关联的物料
        List<MaterialBill> materialBillListUnasso = selectMaterialBillByUnasso(materialBill);
        List<Long> unassoId = materialBillListUnasso.stream().map(m -> {
            return m.getId();
        }).collect(Collectors.toList());
        for (MaterialBill materialBillF : list) {
            //未关联的物料使用更新
            if (unassoId.contains(materialBillF.getId())){
                materialBillF.setParentid(materialBillT.getId());
                materialBillF.setLevel((materialBillT.getLevel()+1));
                materialBillF.setMaterialid(rdaPmsassignRel.getProjectid());
                materialBillMapper.updateMaterialBill(materialBillF);
                updateorderforupdate(Long.parseLong(rdaPmsassignRel.getPmsid()),materialBillF.getMaterialid(),materialBillF.getRank());
                updateRdorder(materialBillF.getMaterialid());
            }else {
                long lt = SnowFlakeUtils.nextId();
                materialBillF.setParentid(materialBillT.getId());
                materialBillF.setId(lt);
                materialBillF.setLevel((materialBillT.getLevel()+1));
                materialBillF.setMaterialid(rdaPmsassignRel.getProjectid());
                materialBillMapper.insertMaterialBill(materialBillF);
                updateorderforupdate(Long.parseLong(rdaPmsassignRel.getPmsid()),materialBillF.getMaterialid(),materialBillF.getRank());
                updateRdorder(materialBillF.getMaterialid());
            }
        }
    }

    /**
     * 插入下一现有零件
     * @param rdaPmsassignRel
     * @return
     */
    public List<MaterialBill> hierarchyUpdate(Sharing rdaPmsassignRel){
        //插入id
        String idsStr=rdaPmsassignRel.getIds();
        String[] ids =idsStr.split(",");
        //获取最顶层的id
        Long tid= Long.valueOf(ids[0]);
        Long tmpdate=new Date().getTime();
        Long tmptime = Long.valueOf(String.valueOf(tmpdate/1000));

        //遍历toid的所有下级节点
        MaterialBill mbT = new MaterialBill();
        mbT.setParentid(Long.parseLong(rdaPmsassignRel.getPmsid()));
        List<MaterialBill> hierarchyList = materialBillMapper.selectMaterialBillList(mbT);

        MaterialBill mbTo = materialBillMapper.selectMaterialBillById(Long.parseLong(rdaPmsassignRel.getPmsid()));
        //表单id
        MaterialBill mbI = materialBillMapper.selectMaterialBillById(tid);
        if (mbTo==null){
            mbI.setParentid(rdaPmsassignRel.getProjectid());
            mbI.setMaterialid(rdaPmsassignRel.getProjectid());
            mbI.setLevel(1);
            List<MaterialBill> hierarchy = getHierarchy(mbI.getId());
            for (MaterialBill materialBill : hierarchy) {
                materialBill.setMaterialid(rdaPmsassignRel.getProjectid());
                materialBillMapper.updateMaterialBill(materialBill);
            }
        }else {
            mbI.setParentid(mbTo.getId());
            mbI.setMaterialid(rdaPmsassignRel.getProjectid());
            mbI.setLevel(mbTo.getLevel()+1);
        }

        //放在集合的第一位
        hierarchyList.remove(mbI);
        hierarchyList.add(0,mbI);

        int[] orderArray = hierarchyList.stream()
                .mapToInt(MaterialBill::getRdorder)
                .toArray();
        Arrays.sort(orderArray);

        //序列号进行重新排序
        for (int i = 0; i < hierarchyList.size(); i++) {
            hierarchyList.get(i).setRdorder(orderArray[i]);
            hierarchyList.get(i).setRank(String.valueOf(orderArray[i]));
            materialBillMapper.updateMaterialBill(hierarchyList.get(i));
        }


        for (MaterialBill materialBill : hierarchyList) {
            updateorderforupdate(materialBill.getParentid(),materialBill.getMaterialid(),materialBill.getRank());
            updateRdorder(materialBill.getMaterialid());
        }


        //遍历id的所有下级节点
        MaterialBill mbId = new MaterialBill();
        mbT.setParentid(rdaPmsassignRel.getProjectid());
        List<MaterialBill> materialBillList = materialBillMapper.selectMaterialBillList(mbId);

        for (MaterialBill materialBill : materialBillList) {
            updateorderforupdate(materialBill.getParentid(),materialBill.getMaterialid(),materialBill.getRank());
            updateRdorder(materialBill.getMaterialid());
        }


        return hierarchyList;
    }



    public void hierarchyUpdates(Sharing rdaPmsassignRel){
        String idsStr=rdaPmsassignRel.getIds();
        //表格id
        MaterialBill materialBillT = selectMaterialBillById(Long.parseLong(rdaPmsassignRel.getPmsid()));
        //表单选中的id
        String[] ids =idsStr.split(",");
        for (String id : ids) {
            MaterialBill materialBillF = selectMaterialBillById(Long.parseLong(id));
            materialBillF.setMaterialid(materialBillT.getMaterialid());
            long sid = SnowFlakeUtils.nextId();
            materialBillF.setId(sid);
            materialBillF.setLevel(materialBillT.getLevel());
            materialBillF.setParentid(materialBillT.getParentid());
            materialBillF.setRank(null);
            int num = materialBillMapper.insertMaterialBill(materialBillF);
            if (num>0){
                updateLevel(materialBillF.getId(),materialBillF.getLevel());
                updateRank(materialBillF.getParentid(),materialBillF.getMaterialid(),materialBillF.getRank());
                updateOrder(materialBillF.getMaterialid());
            }
        }


    }

    /**
     * 插入现有作为上级
     * @param rdaPmsassignRel
     * @return
     */
    public void insertParent(Sharing rdaPmsassignRel){
        String idsStr=rdaPmsassignRel.getIds();
        //表格id
        MaterialBill materialBillT = selectMaterialBillById(Long.parseLong(rdaPmsassignRel.getPmsid()));
        System.out.println("materialBillT==========="+materialBillT);
        //表单选中的id
        String[] ids =idsStr.split(",");
        for (String id : ids) {
            MaterialBill materialBillF = selectMaterialBillById(Long.parseLong(id));
            materialBillF.setMaterialid(materialBillT.getMaterialid());
            long sid = SnowFlakeUtils.nextId();
            materialBillF.setId(sid);
            materialBillF.setLevel(materialBillT.getLevel());
            materialBillF.setParentid(materialBillT.getParentid());
            materialBillF.setRank(null);
            int num = materialBillMapper.insertMaterialBill(materialBillF);
            if (num>0){
                materialBillT.setParentid(sid);
                System.out.println("sid==========="+sid);
                materialBillMapper.updateMaterialBill(materialBillT);
                updateLevel(materialBillF.getId(),materialBillF.getLevel());
                updateRank(materialBillF.getParentid(),materialBillF.getMaterialid(),materialBillF.getRank());
                updateOrder(materialBillF.getMaterialid());
            }
        }

    }

    /**
     * 对比报告
     */
    public List<MaterialBill> compareReport(Long id,String type){
        ArrayList<MaterialBill> materialBills = new ArrayList<>();
        MaterialBill materialBillT = selectMaterialBillById(id);
        materialBills.add(materialBillT);
        //EBOM结构
        if ("1".equals(type)){
            return materialBills;
        }
        //单个层级
        else {
            List<MaterialBill> hierarchy = getHierarchy(id);
            materialBills.addAll(hierarchy);
            return materialBills;
        }
    }


    /**
     * 引用链
     */
    public String ReferenceChain(Long id){
        List<MaterialBill> hierarchyU = getHierarchyU(id);
        Long idr = hierarchyU.get(0).getParentid();
        List<RdaPart> hierarchyR = getHierarchyR(idr);
        for (RdaPart rdaPart : hierarchyR) {
            MaterialBill materialBill = new MaterialBill();
            BeanUtils.copyProperties(rdaPart,materialBill);
            hierarchyU.add(0,materialBill);
        }
        List<String> collect = hierarchyU.stream().map(m -> {
            return m.getName();
        }).collect(Collectors.toList());
        collect.toString();
        return collect.toString();
    }


    /**
     * 根据rda_part查询所有上层级
     * @param id
     * @return
     */
    public List<RdaPart> getHierarchyR(Long id) {
        RdaPart rdaPart = rdaMaterialService.selectRdaPartByid(id);
        List<RdaPart> result = new ArrayList<>();
        if (rdaPart!=null) {
            result.add(rdaPart);
            List<RdaPart> children = getHierarchyR(rdaPart.getParentid());
            result.addAll(children);
        }
        return result;
    }

    // TODO: 2023/11/16 修改原有

    /**
     * 材料清单列表
     */
//    public List<MaterialBill> selectTreeList(MaterialBill materialBill){
//        List<MaterialBill> list = getHierarchy(materialBill.getMaterialid());
//        if (CollectionUtils.isEmpty(list)){
//            RdaPart rdaPart=rdaMaterialService.selectRdaPartByid(materialBill.getMaterialid());
//            if (rdaPart==null){
//                MaterialBill materialBill1 = selectMaterialBillById(materialBill.getMaterialid());
//                list.add(0,materialBill1);
//            }else {
//                MaterialBill bill=new MaterialBill();
//                bill.setLevel(0);
//                bill.setRank(String.valueOf(0));
//                bill.setRdorder(0);
//                bill.setId(rdaPart.getId());
//                bill.setParentid(0L);
//                bill.setMaterialid(rdaPart.getId());
//                bill.setName(rdaPart.getName());
//                bill.setCode(rdaPart.getCode());
//                bill.setDescription(rdaPart.getDescription());
//                bill.setTypeid(Math.toIntExact(rdaPart.getTypeid()));
//                bill.setPolicyid(Math.toIntExact(rdaPart.getPolicyid()));
//                bill.setStateid(Math.toIntExact(rdaPart.getStateid()));
//                list.add(bill);
//            }
//        }else {
//            MaterialBill bill=new MaterialBill();
//            RdaPart rdaPart=rdaMaterialService.selectRdaPartByid(list.get(0).getParentid());
//            if (rdaPart==null){
//                MaterialBill materialBill1 = selectMaterialBillById(list.get(0).getParentid());
//                list.add(0,materialBill1);
//            }else {
//                bill.setLevel(0);
//                bill.setRank(String.valueOf(0));
//                bill.setRdorder(0);
//                bill.setId(rdaPart.getId());
//                bill.setParentid(0L);
//                bill.setMaterialid(rdaPart.getId());
//                bill.setName(rdaPart.getName());
//                bill.setCode(rdaPart.getCode());
//                bill.setDescription(rdaPart.getDescription());
//                bill.setTypeid(Math.toIntExact(rdaPart.getTypeid()));
//                bill.setPolicyid(Math.toIntExact(rdaPart.getPolicyid()));
//                bill.setStateid(Math.toIntExact(rdaPart.getStateid()));
//                list.add(0,bill);
//            }
//        }
//        //过滤条件
//        if (StringUtils.isNotEmpty(materialBill.getSearchValue())){
//            List<MaterialBill> collect = list.stream().filter(m -> m.getName().contains(materialBill.getSearchValue()) || m.getCode().contains(materialBill.getSearchValue()))
//                    .collect(Collectors.toList());
//            if (CollectionUtils.isEmpty(collect)){
//                return null;
//            }else {
//                List<MaterialBill> materialBillList = upStructure(collect);
//                list=materialBillList;
//            }
//        }
//        return list;
//    }

    @Override
    public List<MaterialBill> selectTreeList(MaterialBill materialBill){
        List<MaterialBill> materialBillList = materialBillMapper.selectTreeList(materialBill);
        return materialBillList;
    }

    @Override
    public JSONObject partsList(ServletRequest request) {
        JSONObject jsonobj = new JSONObject();
        //通过任务id获取当前节点id
        ArrayList<String> jsonList=new ArrayList<String>();
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        String projectid=httpRequest.getParameter("projectid");
        MaterialBill materialBill = new MaterialBill();
        materialBill.setProjectid(Long.parseLong(projectid));
        List<Map<String, Object>> maps = materialBillMapper.selectMaterialBillAndRdaPartRel(materialBill);
        maps.forEach(m->{
            StringBuilder json=new StringBuilder();
            String stringJSON = JSON.toJSONString(m);
            json.append(stringJSON);
            RdaPartDynamicattributevalue rdaPartDynamicattributevalue=new RdaPartDynamicattributevalue();
            rdaPartDynamicattributevalue.setObjectid((Long) m.get("id"));
            List<RdaPartDynamicattributevalue> rdaPartDynamicattributevalueList=rdaPartDynamicattributevalueService.selectRdaPartDynamicattributevalueList(rdaPartDynamicattributevalue);
            String attribute = "";
            for(RdaPartDynamicattributevalue partDynamicattributevalue:rdaPartDynamicattributevalueList){
                attribute += ",\""+partDynamicattributevalue.getAttributeName()+"\":\""+partDynamicattributevalue.getAttributeValue()+"\"";//字符串两边含有双引号
            }
            if(attribute!=null && attribute.length()>0){
                json.insert(json.length()-1,attribute);
            }
            jsonList.add(json.toString());
        });

//        materialBillList.forEach((MaterialBill materialBill1)->{
//            StringBuilder json=new StringBuilder();
//            String stringJSON = JSON.toJSONString(materialBill1);
//            json.append(stringJSON);
//            RdaPartDynamicattributevalue rdaPartDynamicattributevalue=new RdaPartDynamicattributevalue();
//            rdaPartDynamicattributevalue.setObjectid(materialBill1.getId());
//            List<RdaPartDynamicattributevalue> rdaPartDynamicattributevalueList=rdaPartDynamicattributevalueService.selectRdaPartDynamicattributevalueList(rdaPartDynamicattributevalue);
//            String attribute = "";
//            for(RdaPartDynamicattributevalue partDynamicattributevalue:rdaPartDynamicattributevalueList){
//                attribute += ",\""+partDynamicattributevalue.getAttributeName()+"\":\""+partDynamicattributevalue.getAttributeValue()+"\"";//字符串两边含有双引号
//            }
//            if(attribute!=null && attribute.length()>0){
//                json.insert(json.length()-1,attribute);
//            }
//            jsonList.add(json.toString());
//        });
        String jarr = JSON.toJSONString(jsonList);
        JSONArray jsonArray = JSONArray.parseArray(jarr);
        List<Object> list = JSON.parseArray(jsonArray.toJSONString(), Object.class);
        List<JSONObject> result = new ArrayList<>();
        for (Object obj : list) {
            JSONObject jsonObject = JSON.parseObject(obj.toString());
            result.add(jsonObject);
        }
        jsonobj.put("rows", result);
        jsonobj.put("total", maps.size());
        return jsonobj;
    }

    @Override
    public void copywbs(List<Sharing> sharing) {
        for (Sharing sharingP : sharing) {
            //复制
            MaterialBill materialBillF = materialBillMapper.selectMaterialBillById(Long.parseLong(sharingP.getFromid()));
            MaterialBill materialBillT = materialBillMapper.selectMaterialBillById(Long.parseLong(sharingP.getToid()));
            materialBillF.setParentid(Long.parseLong(sharingP.getToid()));
            materialBillF.setLevel(materialBillT.getLevel()+1);
            if (1==sharingP.getType()){
                MaterialBill copy = new MaterialBill();
                BeanUtils.copyProperties(materialBillF,copy);
                long id = SnowFlakeUtils.nextId();
                copy.setId(id);
                materialBillMapper.insertMaterialBill(copy);
                updateRank(materialBillT.getId(),materialBillT.getMaterialid(),"");
                updateOrder(materialBillF.getMaterialid());
            }
            //剪切
            else {
                materialBillMapper.updateMaterialBill(materialBillF);
                updateRank(materialBillT.getId(),materialBillT.getMaterialid(),"");
                updateOrder(materialBillF.getMaterialid());
            }
        }
    }

    /**
     * 添加物料表，维护分类属性和物料关系表
     * @param map
     * @return
     */
    @Override
    public int materialAdd(Map<String, Object> map) {
        //库和子库表
        RdaPart rdaPart=new RdaPart();
        //物料表
        MaterialBill materialBill = new MaterialBill();
        //物料关系表
        RdaPartsRel rdaPartsRel = new RdaPartsRel();
        //分类属性键
        ArrayList<String> attribute_key=new ArrayList<String>();//临时存储json键
        //分类属性值
        ArrayList<String> attribute_value=new ArrayList<String>();//临时存储json值
        //将json转换成map循环取键值对
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            if(entry.getKey().equals("code")){
                String attributeValue=(String)entry.getValue();
                materialBill.setCode(attributeValue);
            }else if(entry.getKey().equals("name")){
                String attributeValue=(String)entry.getValue();
                materialBill.setName(attributeValue);
            }else if(entry.getKey().equals("description")){
                String attributeValue=(String)entry.getValue();
                materialBill.setDescription(attributeValue);
            }else if(entry.getKey().equals("ownerid")){
                String attributeValue=(String)entry.getValue();
                materialBill.setOwnerid(Integer.parseInt(attributeValue));
            }else if(entry.getKey().equals("parentid")){
                Long attributeValue=(Long)entry.getValue();
                rdaPartsRel.setParentId(attributeValue);
                materialBill.setParentid(attributeValue);
                materialBill.setMaterialid(attributeValue);
                rdaPartsRel.setToid(attributeValue);
            }else if(entry.getKey().equals("projectid")){
                Long projectid=(Long)entry.getValue();
                Long attributeValue= projectid;
                materialBill.setProjectid(attributeValue);
            }
            else if(entry.getKey().equals("stateid")){
                Long stateid=Long.parseLong(entry.getValue().toString());
                Long attributeValue= stateid;
                materialBill.setStateid(Math.toIntExact(attributeValue));
            }
            else if(entry.getKey().equals("typeid")){
                Long typeid=Long.parseLong(entry.getValue().toString());
                Long attributeValue= typeid;
                materialBill.setTypeid(Math.toIntExact(attributeValue));
                rdaPartsRel.setFromtype(Math.toIntExact(attributeValue));
            }
            else if(entry.getKey().equals("policyid")){
                Long policyid=Long.parseLong(entry.getValue().toString());
                Long attributeValue= policyid;
                materialBill.setPolicyid(Math.toIntExact(attributeValue));
            }
            else if(entry.getKey().equals("number")){
                String value = (String) entry.getValue();
                Double number = Double.parseDouble(value);
                rdaPartsRel.setQuantity(number.longValue());
                materialBill.setNumber(number);
            }else if(entry.getKey().equals("units")){
                String attributeValue=(String)entry.getValue();
                materialBill.setUnits(attributeValue);
            }else if(entry.getKey().equals("nametype")){
                String attributeValue=(String)entry.getValue();
                materialBill.setNametype(attributeValue);
            }
            else{
                String attributeValue=(String)entry.getValue();
                attribute_key.add(entry.getKey());
                attribute_value.add(attributeValue);
            }
        }

        //自动编码
        if (materialBill.getCode() == null) {
            if (materialBill.getNametype()!=null){
                materialBill.setCode(materialBill.getNametype().concat(rdaNameCodeService.getNewCodeNameNo(Long.valueOf(materialBill.getTypeid()), "")));
            }else {
                materialBill.setCode(rdaNameCodeService.getNewCodeNameNo(Long.valueOf(materialBill.getTypeid()),""));
            }
        }
        //区分是否是动态属性
        Map<String,Object> dmap2= WorkspaceUtils.getTypePolicyStates("Classification","1",rdaTypeService,rdaPolicyService,rdaStateService);
        Map<String,Long> dtypeid2=(Map<String,Long>)dmap2.get("Typeid");
        Long typeid2=dtypeid2.get("Part Family");
        List<RdaPart> rdaPartList=rdaMaterialService.selectRdaPartTreeSubordinate(materialBill.getParentid(),typeid2);
        Long ids[]=new Long[rdaPartList.size()];
        for(int i=0;i<rdaPartList.size();i++){
            ids[i]=rdaPartList.get(i).getId();
        }
        List<RdaPartDynamicattribute> rdaPartDynamicattributeList2=rdaPartDynamicattributeService.selectRdaPartDynamicattributeByInIds(ids);
        for(int i=0;i<rdaPartDynamicattributeList2.size();i++){
            RdaPartDynamicattribute partDynamicattribute=rdaPartDynamicattributeList2.get(i);
            for(int j=0;j<attribute_key.size();j++){
                if(partDynamicattribute.getAttributeName().equals(attribute_key.get(j))){
                    Long dynamicattributeId=partDynamicattribute.getId();
                    RdaPartDynamicattributevalue rdaPartDynamicattributevalue=new RdaPartDynamicattributevalue();
                    rdaPartDynamicattributevalue.setId(SnowFlakeUtils.nextId());
                    rdaPartDynamicattributevalue.setOwnerid(SecurityUtils.getUserId());
                    rdaPartDynamicattributevalue.setDynamicattributeid(dynamicattributeId);
                    rdaPartDynamicattributevalue.setCreateTime(DateUtils.getNowDate());
                    rdaPartDynamicattributevalue.setObjectid(SnowFlakeUtils.nextId());
                    rdaPartDynamicattributevalue.setAttributeValue(attribute_value.get(j));
                    rdaPartDynamicattributevalueService.insertRdaPartDynamicattributevalue(rdaPartDynamicattributevalue);
                }
            }
        }
        Map<String,Object> dmap= WorkspaceUtils.getTypePolicyStates("EC Part","1",rdaTypeService,rdaPolicyService,rdaStateService);
        Map<String,Long> dtypeid=(Map<String,Long>)dmap.get("Typeid");
        Long typeid=dtypeid.get("Part");
        Long dPolicyid=(Long)dmap.get("Policyid");
        String revision=dmap.get("revision").toString();
        Map<String,Object> dstateMap=(Map)dmap.get("Stateid");
        Long dstateid=(Long)dstateMap.get("Preliminary");
        materialBill.setId(SnowFlakeUtils.nextId());
        materialBill.setTypeid(Math.toIntExact(typeid));
        materialBill.setPolicyid(Math.toIntExact(dPolicyid));
        materialBill.setStateid(Math.toIntExact(dstateid));
        materialBill.setLevel(0);
        materialBill.setOwnerid(Integer.parseInt(SecurityUtils.getUserId().toString()));
        materialBill.setRank("0");
        materialBill.setRevision(revision);

        rdaPartsRel.setId(SnowFlakeUtils.nextId());
        rdaPartsRel.setRelName("subclass");
        rdaPartsRel.setFromid(materialBill.getId());
        rdaPartsRel.setTotype(Math.toIntExact(typeid2));
        rdaPartsRel.setFindnumber("0");
        rdaPartsRel.setLevel(0L);
//        rdaWorkflowTempleteScopeService.createWorkflowWithObject(typeid,dPolicyid,dstateid,SnowFlakeUtils.nextId(),"part",rdaPart.getName());
        rdaPartsRelService.insertRdaPartsRel(rdaPartsRel);

        MaterialBill materialBillC = new MaterialBill();
        materialBillC.setName(materialBill.getName());
        materialBillC.setCode(materialBill.getCode());
        materialBillC.setRevision(materialBill.getRevision());
        List<MaterialBill> materialBillList = materialBillMapper.selectMaterialBillList(materialBillC);
        if (materialBillList.size()>0){
            throw new ServiceException("有相同物料");

        }
        return materialBillMapper.insertMaterialBill(materialBill);
    }

    /**
     * 根据单个或多个物料返回上层结构
     */
    public List<MaterialBill> upStructure(List<MaterialBill> materialBills){
        List<MaterialBill> list = new ArrayList<>();
        RdaPart rdaPart=rdaMaterialService.selectRdaPartByid(materialBills.get(0).getMaterialid());
        MaterialBill bill=new MaterialBill();
        bill.setLevel(0);
        bill.setRank(String.valueOf(0));
        bill.setRdorder(0);
        bill.setId(rdaPart.getId());
        bill.setParentid(0L);
        bill.setMaterialid(rdaPart.getId());
        bill.setName(rdaPart.getName());
        bill.setCode(rdaPart.getCode());
        bill.setDescription(rdaPart.getDescription());
        bill.setTypeid(Math.toIntExact(rdaPart.getTypeid()));
        bill.setPolicyid(Math.toIntExact(rdaPart.getPolicyid()));
        bill.setStateid(Math.toIntExact(rdaPart.getStateid()));
        for (MaterialBill materialBill : materialBills) {
            List<MaterialBill> hierarchyU = getHierarchyU(materialBill.getId());
            for (MaterialBill materialBill1 : hierarchyU) {
                if (!list.contains(materialBill1)){
                    list.add(materialBill1);
                }
            }
        }
        list.add(0,bill);
        return list;
    }


    /**
     * copyTo复制到
     * 材料清单中选中A，弹出界面中搜索零件B，A放在B下面
     */

    public void copyTo(Sharing rdaRestrainwbsRel){
        String idsStr=rdaRestrainwbsRel.getIds();
        String[] ids =idsStr.split(",");
        Long fid= Long.valueOf(ids[0]);
        //表单选中的id
        MaterialBill materialBillF = selectMaterialBillById(fid);
        //表格选中的id
        MaterialBill materialBillT;
        //这是个根节点
        if (materialBillF==null){
            materialBillT=selectMaterialBillById(Long.parseLong(rdaRestrainwbsRel.getToid()));
            //查询表格选中的所有下级
            List<MaterialBill> hierarchy = getHierarchy(Long.parseLong(rdaRestrainwbsRel.getToid()));
            //雪花id
            long lt = SnowFlakeUtils.nextId();
            //存放id对比关系
            HashMap<Long, Long> toId = new HashMap<>();
            materialBillT.setId(lt);
            materialBillT.setLevel(1);
            materialBillT.setMaterialid(fid);
            materialBillT.setParentid(fid);
            materialBillMapper.insertMaterialBill(materialBillT);
            for (MaterialBill materialBill : hierarchy) {
                long l = SnowFlakeUtils.nextId();
                toId.put(materialBill.getId(),l);
            }
            for (MaterialBill materialBill : hierarchy) {
                materialBill.setId(toId.get(materialBill.getId()));
                materialBill.setMaterialid(fid);
                materialBill.setParentid(toId.get(materialBill.getParentid())==null?lt:toId.get(materialBill.getParentid()));
                materialBillMapper.insertMaterialBill(materialBill);
            }
            updateorderforupdate(fid,fid,"");
            updateRdorder(fid);
        }else {
            materialBillT=selectMaterialBillById(Long.parseLong(rdaRestrainwbsRel.getToid()));
            //查询表格选中的所有下级
            List<MaterialBill> hierarchy = getHierarchy(Long.parseLong(rdaRestrainwbsRel.getToid()));
            //雪花id
            long lt = SnowFlakeUtils.nextId();
            //存放id对比关系
            HashMap<Long, Long> toId = new HashMap<>();
            materialBillT.setId(lt);
            materialBillT.setLevel(materialBillF.getLevel()+1);
            materialBillT.setMaterialid(materialBillF.getMaterialid());
            materialBillT.setParentid(materialBillF.getId());
            materialBillMapper.insertMaterialBill(materialBillT);
            for (MaterialBill materialBill : hierarchy) {
                long l = SnowFlakeUtils.nextId();
                toId.put(materialBill.getId(),l);
            }
            for (MaterialBill materialBill : hierarchy) {
                materialBill.setId(toId.get(materialBill.getId()));
                materialBill.setMaterialid(fid);
                materialBill.setParentid(toId.get(materialBill.getParentid())==null?lt:toId.get(materialBill.getParentid()));
                materialBillMapper.insertMaterialBill(materialBill);
            }
            updateorderforupdate(materialBillF.getId(),materialBillF.getMaterialid(),materialBillF.getRank());
            updateRdorder(materialBillF.getMaterialid());
        }
        return;
    }


    /**
     * 引用者
     *
     */
    public List<MaterialBill> referrer(MaterialBill materialBill){
        ArrayList<MaterialBill> list = new ArrayList<>();

        //如何是最上层，找rda_part
        MaterialBill materialBillT = selectMaterialBillById(materialBill.getId());
        if (materialBillT==null){
            return list;
        }
        //查找有可能的上层(根据code)
        MaterialBill materialBillM = new MaterialBill();
        materialBillM.setCode(materialBillT.getCode());
        List<MaterialBill> materialBillList = selectMaterialBillList(materialBillM);
        System.out.println("MaterialBill===同个物料"+materialBillList.size()+"==="+materialBillList);
        for (MaterialBill bill : materialBillList) {
            if (selectMaterialBillById(bill.getParentid())==null){
                System.out.println("有个是最顶层====");
                RdaPart rdaPart=rdaMaterialService.selectRdaPartByid(bill.getParentid());
                System.out.println("rdaPart======="+rdaPart);
                MaterialBill materialBill1 = new MaterialBill();
                BeanUtils.copyProperties(rdaPart,materialBill1);
                list.add(materialBill1);
            }else {
                list.add(selectMaterialBillById(bill.getParentid()));
            }

        }

        return list;
    }


}
